import sqlite3
import threading


class DBConnection:
    def __init__(self, path):
        self._lock = threading.RLock()
        self._connection = sqlite3.connect(path)
        cursor = self._connection.cursor()
        try:
            cursor.execute(
                "create table if not exists user_info (title varchar(50) not null unique, url varchar(255) not null)")
        finally:
            cursor.close()

    def execute(self, sql):
        cursor = self._connection.cursor()
        try:
            print(sql)
            result = cursor.execute(sql)
            return result.lastrowid
        finally:
            self._connection.commit()
            cursor.close()

    def __enter__(self):
        self._lock.acquire()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._lock.release()

    def __del__(self):
        self._connection.close()


connection = DBConnection("./douban.sqlite3")
